package com.xujie.sportsmeeting.controller;

import com.xujie.sportsmeeting.common.result.Result;
import com.xujie.sportsmeeting.service.StatisticsService;
import com.xujie.sportsmeeting.vo.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 统计分析控制器
 */
@Tag(name = "统计分析管理", description = "各类统计分析和报表生成接口")
@RestController
@RequestMapping("/statistics")
@RequiredArgsConstructor
public class StatisticsController {

    private final StatisticsService statisticsService;

    @Operation(summary = "获取系统概览统计")
    @GetMapping("/overview")
    @PreAuthorize("hasAnyAuthority('system:user', 'statistics')")
    public Result<SystemOverviewVO> getSystemOverview() {
        SystemOverviewVO overview = statisticsService.getSystemOverview();
        return Result.success(overview);
    }

    @Operation(summary = "获取个人成绩统计")
    @GetMapping("/athlete/{athleteId}")
    @PreAuthorize("hasAnyAuthority('system:user', 'statistics', 'athlete')")
    public Result<AthleteStatisticsVO> getAthleteStatistics(@PathVariable Long athleteId) {
        AthleteStatisticsVO statistics = statisticsService.getAthleteStatistics(athleteId);
        if (statistics == null) {
            return Result.error("运动员不存在");
        }
        return Result.success(statistics);
    }

    @Operation(summary = "获取项目成绩统计")
    @GetMapping("/event/{eventId}")
    @PreAuthorize("hasAnyAuthority('system:user', 'statistics', 'judge')")
    public Result<EventStatisticsVO> getEventStatistics(@PathVariable Long eventId) {
        EventStatisticsVO statistics = statisticsService.getEventStatistics(eventId);
        if (statistics == null) {
            return Result.error("项目不存在");
        }
        return Result.success(statistics);
    }

    @Operation(summary = "获取院系团体成绩统计")
    @GetMapping("/department")
    @PreAuthorize("hasAnyAuthority('system:user', 'statistics', 'judge')")
    public Result<List<TeamStatisticsVO>> getDepartmentStatistics() {
        List<TeamStatisticsVO> statistics = statisticsService.getDepartmentStatistics();
        return Result.success(statistics);
    }

    @Operation(summary = "获取班级团体成绩统计")
    @GetMapping("/class")
    @PreAuthorize("hasAnyAuthority('system:user', 'statistics', 'judge')")
    public Result<List<TeamStatisticsVO>> getClassStatistics(
            @RequestParam(required = false) String department) {
        List<TeamStatisticsVO> statistics = statisticsService.getClassStatistics(department);
        return Result.success(statistics);
    }

    @Operation(summary = "获取奖牌榜统计")
    @GetMapping("/medals")
    public Result<List<MedalStatisticsVO>> getMedalStatistics(
            @RequestParam(defaultValue = "1") Integer statisticsType) {
        List<MedalStatisticsVO> statistics = statisticsService.getMedalStatistics(statisticsType);
        return Result.success(statistics);
    }

    @Operation(summary = "获取参赛情况统计")
    @GetMapping("/participation")
    @PreAuthorize("hasAnyAuthority('system:user', 'statistics', 'judge')")
    public Result<ParticipationStatisticsVO> getParticipationStatistics() {
        ParticipationStatisticsVO statistics = statisticsService.getParticipationStatistics();
        return Result.success(statistics);
    }

    @Operation(summary = "获取项目热度统计")
    @GetMapping("/event-popularity")
    public Result<List<EventPopularityVO>> getEventPopularityStatistics() {
        List<EventPopularityVO> statistics = statisticsService.getEventPopularityStatistics();
        return Result.success(statistics);
    }

    @Operation(summary = "获取成绩趋势分析")
    @GetMapping("/score-trend")
    @PreAuthorize("hasAnyAuthority('system:user', 'statistics', 'judge')")
    public Result<List<ScoreTrendVO>> getScoreTrend(
            @RequestParam Long eventId,
            @RequestParam(defaultValue = "7d") String timeRange) {
        List<ScoreTrendVO> trends = statisticsService.getScoreTrend(eventId, timeRange);
        return Result.success(trends);
    }

    @Operation(summary = "获取性别参与统计")
    @GetMapping("/gender")
    @PreAuthorize("hasAnyAuthority('system:user', 'statistics')")
    public Result<GenderStatisticsVO> getGenderStatistics() {
        GenderStatisticsVO statistics = statisticsService.getGenderStatistics();
        return Result.success(statistics);
    }

    @Operation(summary = "获取院系参与度排名")
    @GetMapping("/department-participation")
    @PreAuthorize("hasAnyAuthority('system:user', 'statistics')")
    public Result<List<DepartmentParticipationVO>> getDepartmentParticipationRanking() {
        List<DepartmentParticipationVO> ranking = statisticsService.getDepartmentParticipationRanking();
        return Result.success(ranking);
    }

    @Operation(summary = "获取实时排行榜")
    @GetMapping("/ranking")
    public Result<List<RankingVO>> getRealTimeRanking(
            @RequestParam(defaultValue = "total") String rankingType,
            @RequestParam(defaultValue = "10") Integer limit) {
        List<RankingVO> ranking = statisticsService.getRealTimeRanking(rankingType, limit);
        return Result.success(ranking);
    }

    @Operation(summary = "获取成绩分布统计")
    @GetMapping("/score-distribution/{eventId}")
    @PreAuthorize("hasAnyAuthority('system:user', 'statistics', 'judge')")
    public Result<ScoreDistributionVO> getScoreDistribution(@PathVariable Long eventId) {
        ScoreDistributionVO distribution = statisticsService.getScoreDistribution(eventId);
        return Result.success(distribution);
    }

    @Operation(summary = "获取破纪录统计")
    @GetMapping("/record-breaking")
    public Result<List<RecordBreakingVO>> getRecordBreakingStatistics() {
        List<RecordBreakingVO> records = statisticsService.getRecordBreakingStatistics();
        return Result.success(records);
    }

    @Operation(summary = "重新计算团体成绩统计")
    @PostMapping("/recalculate")
    @PreAuthorize("hasAnyAuthority('system:user', 'statistics')")
    public Result<String> recalculateTeamStatistics() {
        boolean success = statisticsService.recalculateTeamStatistics();
        if (success) {
            return Result.success("重新计算完成", "重新计算完成");
        } else {
            return Result.<String>error("计算失败");
        }
    }

    @Operation(summary = "生成统计报表数据")
    @PostMapping("/report")
    @PreAuthorize("hasAnyAuthority('system:user', 'statistics')")
    public Result<Map<String, Object>> generateReportData(
            @RequestParam String reportType,
            @RequestBody(required = false) Map<String, Object> params) {
        Map<String, Object> reportData = statisticsService.generateReportData(reportType, params);
        return Result.success(reportData);
    }

    @Operation(summary = "导出统计数据")
    @GetMapping("/export")
    @PreAuthorize("hasAnyAuthority('system:user', 'statistics')")
    public Result<String> exportStatisticsData(
            @RequestParam String exportType,
            @RequestParam(required = false) Map<String, Object> params) {
        try {
            statisticsService.exportStatisticsData(exportType, params);
            // TODO: 实现文件上传到云存储或本地存储，返回下载链接
            String downloadUrl = "https://example.com/download/" + System.currentTimeMillis() + "." + exportType;
            return Result.success("导出成功", downloadUrl);
        } catch (Exception e) {
            return Result.<String>error("导出失败：" + e.getMessage());
        }
    }

    @Operation(summary = "获取统计数据字典")
    @GetMapping("/dictionary")
    public Result<Map<String, Object>> getStatisticsDictionary() {
        Map<String, Object> dictionary = Map.of(
            "statisticsTypes", List.of(
                Map.of("value", 1, "label", "院系统计"),
                Map.of("value", 2, "label", "班级统计")
            ),
            "rankingTypes", List.of(
                Map.of("value", "total", "label", "总积分排名"),
                Map.of("value", "medal", "label", "奖牌排名"),
                Map.of("value", "participation", "label", "参与度排名")
            ),
            "timeRanges", List.of(
                Map.of("value", "1d", "label", "最近1天"),
                Map.of("value", "7d", "label", "最近7天"),
                Map.of("value", "30d", "label", "最近30天"),
                Map.of("value", "all", "label", "全部时间")
            ),
            "exportTypes", List.of(
                Map.of("value", "excel", "label", "Excel表格"),
                Map.of("value", "pdf", "label", "PDF报告"),
                Map.of("value", "csv", "label", "CSV数据")
            )
        );
        
        return Result.success(dictionary);
    }

    @Operation(summary = "获取快速统计卡片数据")
    @GetMapping("/quick-stats")
    public Result<Map<String, Object>> getQuickStats() {
        SystemOverviewVO overview = statisticsService.getSystemOverview();
        
        Map<String, Object> quickStats = Map.of(
            "totalAthletes", Map.of(
                "value", overview.getTotalAthletes(),
                "label", "运动员总数",
                "icon", "👤",
                "color", "#1890ff"
            ),
            "totalEvents", Map.of(
                "value", overview.getTotalEvents(),
                "label", "比赛项目",
                "icon", "🏃",
                "color", "#52c41a"
            ),
            "totalRegistrations", Map.of(
                "value", overview.getTotalRegistrations(),
                "label", "报名总数",
                "icon", "📝",
                "color", "#faad14"
            ),
            "totalScores", Map.of(
                "value", overview.getTotalScores(),
                "label", "成绩录入",
                "icon", "🏆",
                "color", "#f5222d"
            )
        );
        
        return Result.success(quickStats);
    }
}
